const Koa = require('koa')
const Router = require('koa-router')
const bodyparser = require('koa-bodyparser')
const cors = require('koa-cors')
const app = new Koa()
const router = new Router()

const list = [
    {
        id:1,
        title: "武动乾坤"
    },
    {
        id:2,
        title: "大主宰"
    },
    {
        id:3,
        title: "斗破苍穹"
    },
    {
        id:4,
        title: "少妇白洁"
    },
    {
        id:5,
        title: "少年阿宾"
    },
    {
        id:6,
        title: "雨后小故事"
    }
]
// app.use(cors({
//     origin: "http://localhost:8080"
//     // origin: "*"
// }))




// get 获取  post 新增  put编辑 delete删除

// get    =>   query||params
// post    =>   body||params
// put    =>   body||params
// delete    =>   body||params

// query
// 传  /list?id=1&name=kkk
// 取 ctx.query

// params
// 传 /list/1/kkk    定义 /list/:id/:name
// 取 ctx.params

// body
// 传 json格式的body
// 取 ctx.request.body




















// get不能使用body 只能使用 query params
// query传参  localhost:8888/list?id=1&name='kkk'    queryString 
// query取值   ctx.query  =  {id:'1',name:'kkk'}
router.get('/list', async (ctx)=>{
    // 分页 模糊查询 排序 asc正序 desc倒叙
    const {pageIndex,pageSize, keyword = '', sortType='asc'} = ctx.query;
    console.log(pageIndex,pageSize)
    // 1 2 3 4 5 6 7 8
    // slice(0, 3)
    // slice(3, 6)
    let newList = []
    newList = list
                .filter(item=>item.title.includes(keyword))
                .slice((pageIndex-1)*pageSize, pageIndex*pageSize)
                .sort((a,b)=>sortType==='asc'?a.id-b.id: b.id-a.id )
    ctx.body = newList
})
// body
router.post('/list', async (ctx)=>{
    const {title} = ctx.request.body;
    list.push({
        id:Date.now(),
        title
    })
    ctx.body = '添加成功'
})
// 
router.put('/list', async (ctx)=>{
    const {id,title} = ctx.request.body;
    let bool = false;
    list.forEach((item,index)=>{
        if(item.id===id) {
            bool = true
            list[index].title = title
        }
    })
    ctx.response.body = bool?'编辑成功':"编辑失败"
})
// params
router.delete('/list/:id', async (ctx)=>{
    const {id} = ctx.params;
    const ind = list.findIndex(item => item.id == id)
    if(ind===-1){
        ctx.body = '删除失败'
    } else {
        list.splice(ind,1)
        ctx.body = '删除成功'
    }
})

app.use(bodyparser()) // 必须放到router之前
app.use(router.routes()) // 挂载路由中间件

app.listen(8888, () => {
    console.log('listen to 8888')
})